package com.atcookie.wc;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;


/**
 * DastaSet Api 实现 wordCount
 */
public class WordCountBatchDemo {
    public static void main(String[] args) throws Exception {
        //1 创建执行环境
        ExecutionEnvironment environment = ExecutionEnvironment.getExecutionEnvironment();

        //2 读取数据，：从文件中读取数据
        DataSource<String> dataSource = environment.readTextFile("FlinkTutorial-1.17/input/word.txt");

        //3 切分、转换
        FlatMapOperator<String, Tuple2<String, Integer>> stringTuple2FlatMapOperator = dataSource.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            //collector 是收集器
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] s1 = s.split(" ");
                for (String str : s1) {
                    collector.collect(Tuple2.of(str, 1));
                }
            }
        });

        //4 按照word分组
        UnsortedGrouping<Tuple2<String, Integer>> tuple2UnsortedGrouping = stringTuple2FlatMapOperator.groupBy(0);//按照位置0的字段分组
        //5 个分组内聚合
        AggregateOperator<Tuple2<String, Integer>> sum = tuple2UnsortedGrouping.sum(1);//1代表tuole中的位置。按照位置的1的字段聚合
        //6 输出
        sum.print();
    }

}
